//
//  ReplayKitExample+Recording.swift
//  SwiftCode
//
//  Created by yuhus on 2023/9/21.
//  主要用于录制 App 内容，可过滤系统通知和键盘等 UIView。

import Foundation
import ReplayKit

extension ReplayKitExample: RPPreviewViewControllerDelegate {
  @objc func recordButtonTapped() {
    if isActive == false {
      startRecording()
    } else {
      stopRecording()
    }
  }
  
  private func startRecording() {
    guard RPScreenRecorder.shared().isAvailable else { return }
    
    RPScreenRecorder.shared().startRecording { error in
      if let error {
        Timber.d(error)
        return
      }
      
      self.setRecordingState(active: true)
      self.setupCameraView()
    }
  }
  
  private func stopRecording() {
    RPScreenRecorder.shared().stopRecording { [weak self] previewer, error in
      guard let self else { return }
      
      self.setRecordingState(active: false)
      self.tearDownCameraView()
      
      guard let previewer, error == nil else {
        Timber.d(error ?? "RPPreviewViewController is nil")
        return
      }
      
      if let movieURL = previewer.value(forKey: "movieURL") as? URL {
        Timber.d(movieURL)
        self.present(ShareViewController(with: .video(movieURL)), animated: true)
      } else {
        previewer.previewControllerDelegate = self
        self.present(previewer, animated: true)
      }
    }
  }
  
  @available(iOS 14.0, *)
  private func stopRecording(with outputURL: URL) {
    RPScreenRecorder.shared().stopRecording(withOutput: outputURL) { [weak self] error in
      guard let self else { return }
      
      self.setRecordingState(active: false)
      self.tearDownCameraView()
      
      if let error {
        Timber.e(error)
        return
      }
      Timber.d(outputURL)
      DispatchQueue.main.async {
        self.present(ShareViewController(with: .video(outputURL)), animated: true)
      }
    }
  }
  
  private func setRecordingState(active: Bool) {
    DispatchQueue.main.async {
      if active == true {
        self.recordButton.setTitle("Stop Recording", for: .normal)
        self.startTiming()
      } else {
        self.recordButton.setTitle("Start Recording", for: .normal)
        self.stopTiming()
      }
      
      // Set the internal recording state.
      self.isActive = active
    }
  }
  
  func previewControllerDidFinish(_ previewController: RPPreviewViewController) {
    previewController.dismiss(animated: true)
  }
}
